import os

from loguru import logger
from common.utils import create_dir
from common.globalconfig import global_config

__all__ = [
    "logger",
    "logger_file",
    "logger_output"
]
logger = logger.opt()
log = logger


# 创建日志文件名
def logger_file(path: str , name="") -> str:
    """ 创建日志文件名 """
    log_path = create_dir( "/" + name)
    """ 保留日志文件夹下最大个数(本地调试用) 
    本地调式需要多次重启, 日志轮转片不会生效 """
    file_list = os.listdir(log_path)
    if len(file_list) > 200:
        try:
            os.remove(os.path.join(log_path, file_list[-1]))
        except Exception as e:
            logger.error(e)
    # 日志输出路径
    return os.path.join(log_path, path)


def logger_output(file_name=f"{__package__}/{os.path.basename(__file__)}", _logger=logger):
    """输出文件"""
    _logger.add(
        logger_file(name=file_name),
        encoding=global_config.GLOBAL_ENCODING,
        mode=global_config.LOGGER_MODE,
        level=global_config.LOGGER_LEVEL,
        rotation=global_config.LOGGER_ROTATION,
        retention=global_config.LOGGER_RETENTION,
        format=global_config.LOGGER_FORMAT,
        enqueue=True
    )


log.info("全局日志加载")
log.info(f"当前激活配置为：{global_config.active}")
